﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Xml.XPath;
using TheOutfield.UmbExt.UniversalMediaPicker.Xslt;
using TheOutfield.UmbExt.UniversalMediaPicker.Extensions;
using umbraco;

namespace TheOutfield.UmbExt.UniversalMediaPicker.Providers.Screenr
{
    public class ScreenrXsltExtension : AbstractXsltExtension
    {
        public static XPathNodeIterator GetMedia(int docTypeDefinitionId, string id)
        {
            var service = GetProvider<ScreenrProvider>(docTypeDefinitionId).Service;

            try
            {
                var video = service.GetVideo(id);

                var xd = new XmlDocument();
                var docNode = xmlHelper.addTextNode(xd, "Video", "");

                if (video != null)
                {
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Link", video.Link));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Title", video.Title));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Width", video.Width.ToString()));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Height", video.Height.ToString()));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Author", video.Author));
                    docNode.AppendChild(xmlHelper.addCDataNode(xd, "EmbedCode", video.EmbedCode));
                }

                xd.AppendChild(docNode);

                return xd.CreateNavigator().Select("/Video");
            }
            catch (Exception e)
            {
                return e.ToXPathNodeIterator();
            }
        }
    }
}